#include "ctcpupdate.h"
#include <QDataStream>
#include <QDomElement>
#include <QFile>
#include <QNetworkInterface>
#include <QIODevice>
#include "module/const_define.h"
#include "serversetting.h"

CTcpUpdate::CTcpUpdate(QObject *parent) :
    QTcpServer(parent)
{    
    setMaxPendingConnections(1);
    connect(this, SIGNAL(newConnection()), this, SLOT(newConnect()));
}

void CTcpUpdate::startServer()
{
    if(this->listen(QHostAddress::Any,GATEWAY_LOCAL_LISTEN))
    {
       qDebug() << QString("TcpUpdate server is listening......");
    }
    else
    {
        qDebug() << "TcpUpdate start fail, port 9001 is already occupied, try again !";
    }
}

void CTcpUpdate::stopServer()
{
    this->close();
}

void CTcpUpdate::newConnect()
{
    m_tcpsocket = nextPendingConnection();
    connect(m_tcpsocket,SIGNAL(readyRead()),this,SLOT(sendMessage()));
    connect(m_tcpsocket, SIGNAL(disconnected()),m_tcpsocket, SLOT(deleteLater()));
}

void CTcpUpdate::sockDisconnect()
{
    m_tcpsocket->disconnectFromHost();
    m_tcpsocket->deleteLater();
    m_tcpsocket = NULL;
}

void CTcpUpdate::sendMessage()    //是connect中的槽函数
{
    QByteArray cmdBytes,dataByte;

    if (m_tcpsocket->bytesAvailable() < (int)sizeof(quint16))
        return;

    int length = 0;
    QIODevice *_io_s = static_cast<QIODevice *>(m_tcpsocket);
    QDataStream s(_io_s);
    s >> cmdBytes >> length >> dataByte;


    QDomDocument domTree;
    QString errorMsg ;
    int errorLine;
    int errorColumn;

    if (!domTree.setContent( cmdBytes,false, &errorMsg , &errorLine , &errorColumn ) )
    {
        qDebug()<< QString(cmdBytes);
        qDebug() << "XML格式错误,msg: " << errorMsg << "line " << errorLine;
        return ;
    }
    else
    {
        qDebug()<< "get update cmd " <<  QString(cmdBytes);
    }

    QDomElement ele = domTree.documentElement();
    QString cmdStr = ele.tagName();
    QByteArray updateByteArray;

    if(cmdStr == "reqVersion")
    {
        updateByteArray = QString("Version %1").arg(g_version).toLocal8Bit();
    }
    else if(cmdStr == "reqGatewayConfig")
    {
        QString fileName = "config.ini";

        if(!fileName.isEmpty())
        {
            QFile file(fileName);
            if(file.open(QFile::ReadWrite))
            {
                updateByteArray = file.readAll();
                file.close();
            }
        }
    }
    else if(cmdStr == "setGatewayConfig")
    {
        if(length == dataByte.size())
        {
            QString fileName = "config.ini";

            QFile file(fileName);
            if(file.open(QFile::ReadWrite))
            {
                file.resize(0);
                file.write(dataByte);
                file.close();

                m_tcpsocket->write("ok");
                m_tcpsocket->flush();

                emit s_settingChange();
            }
        }

        return ;
    }

    QByteArray sendData;
    QDataStream stream(&sendData,QIODevice::ReadWrite);
    stream << updateByteArray.length() << updateByteArray;

    m_tcpsocket->write(sendData);
    m_tcpsocket->flush();
}

